/**
 * 性能监控工具
 * 提供页面加载、API请求、内存使用等性能指标监控
 */

// 性能指标接口
export interface PerformanceMetrics {
  pageLoadTime: number;
  apiResponseTime: number;
  memoryUsage: number;
  renderTime: number;
  timestamp: number;
}

// 页面性能数据
export interface PagePerformance {
  pageName: string;
  loadStartTime: number;
  loadEndTime: number;
  renderStartTime: number;
  renderEndTime: number;
  apiCalls: APICallMetrics[];
}

// API调用性能数据
export interface APICallMetrics {
  url: string;
  method: string;
  startTime: number;
  endTime: number;
  responseTime: number;
  success: boolean;
  errorMessage?: string;
}

/**
 * 性能监控器类
 */
export class PerformanceMonitor {
  private static instance: PerformanceMonitor;
  private pageMetrics = new Map<string, PagePerformance>();
  private apiMetrics: APICallMetrics[] = [];
  private memoryCheckInterval?: NodeJS.Timeout;
  
  private constructor() {
    this.startMemoryMonitoring();
  }
  
  static getInstance(): PerformanceMonitor {
    if (!this.instance) {
      this.instance = new PerformanceMonitor();
    }
    return this.instance;
  }
  
  /**
   * 开始页面性能监控
   */
  startPageMonitoring(pageName: string): void {
    const now = Date.now();
    
    this.pageMetrics.set(pageName, {
      pageName,
      loadStartTime: now,
      loadEndTime: 0,
      renderStartTime: now,
      renderEndTime: 0,
      apiCalls: []
    });
    
    console.log(`📊 开始监控页面性能: ${pageName}`);
  }
  
  /**
   * 结束页面加载监控
   */
  endPageLoading(pageName: string): void {
    const pageMetric = this.pageMetrics.get(pageName);
    if (pageMetric) {
      pageMetric.loadEndTime = Date.now();
      const loadTime = pageMetric.loadEndTime - pageMetric.loadStartTime;
      
      console.log(`⏱️ 页面 ${pageName} 加载完成，耗时: ${loadTime}ms`);
      
      // 如果加载时间过长，给出警告
      if (loadTime > 3000) {
        console.warn(`⚠️ 页面 ${pageName} 加载时间过长: ${loadTime}ms`);
      }
    }
  }
  
  /**
   * 结束页面渲染监控
   */
  endPageRendering(pageName: string): void {
    const pageMetric = this.pageMetrics.get(pageName);
    if (pageMetric) {
      pageMetric.renderEndTime = Date.now();
      const renderTime = pageMetric.renderEndTime - pageMetric.renderStartTime;
      
      console.log(`🎨 页面 ${pageName} 渲染完成，耗时: ${renderTime}ms`);
      
      // 如果渲染时间过长，给出警告
      if (renderTime > 2000) {
        console.warn(`⚠️ 页面 ${pageName} 渲染时间过长: ${renderTime}ms`);
      }
    }
  }
  
  /**
   * 记录API调用性能
   */
  recordAPICall(metrics: APICallMetrics): void {
    this.apiMetrics.push(metrics);
    
    // 限制记录数量
    if (this.apiMetrics.length > 100) {
      this.apiMetrics.shift();
    }
    
    console.log(`🌐 API调用: ${metrics.method} ${metrics.url}, 耗时: ${metrics.responseTime}ms`);
    
    // 如果API响应时间过长，给出警告
    if (metrics.responseTime > 5000) {
      console.warn(`⚠️ API响应时间过长: ${metrics.url}, 耗时: ${metrics.responseTime}ms`);
    }
    
    // 记录到对应页面
    for (const [, pageMetric] of this.pageMetrics) {
      if (pageMetric.loadEndTime === 0) { // 页面还在加载中
        pageMetric.apiCalls.push(metrics);
        break;
      }
    }
  }
  
  /**
   * 开始内存监控
   */
  private startMemoryMonitoring(): void {
    // 每30秒检查一次内存使用情况
    this.memoryCheckInterval = setInterval(() => {
      this.checkMemoryUsage();
    }, 30000);
  }
  
  /**
   * 检查内存使用情况
   */
  private checkMemoryUsage(): void {
    // #ifdef H5
    if (typeof performance !== 'undefined' && (performance as any).memory) {
      const memory = (performance as any).memory;
      const usedMB = Math.round(memory.usedJSHeapSize / 1024 / 1024);
      const totalMB = Math.round(memory.totalJSHeapSize / 1024 / 1024);
      const limitMB = Math.round(memory.jsHeapSizeLimit / 1024 / 1024);
      
      console.log(`💾 内存使用: ${usedMB}MB / ${totalMB}MB (限制: ${limitMB}MB)`);
      
      // 内存使用率超过80%时警告
      if (usedMB / limitMB > 0.8) {
        console.warn(`⚠️ 内存使用率过高: ${Math.round(usedMB / limitMB * 100)}%`);
        this.suggestMemoryOptimization();
      }
    }
    // #endif
  }
  
  /**
   * 内存优化建议
   */
  private suggestMemoryOptimization(): void {
    console.group('💡 内存优化建议');
    console.log('1. 检查是否有未清理的定时器');
    console.log('2. 检查是否有未取消的事件监听器');
    console.log('3. 检查是否有循环引用导致的内存泄漏');
    console.log('4. 考虑使用虚拟滚动优化长列表');
    console.groupEnd();
  }
  
  /**
   * 获取页面性能报告
   */
  getPagePerformanceReport(pageName: string): PagePerformance | null {
    return this.pageMetrics.get(pageName) || null;
  }
  
  /**
   * 获取所有页面性能报告
   */
  getAllPagePerformanceReports(): PagePerformance[] {
    return Array.from(this.pageMetrics.values());
  }
  
  /**
   * 获取API性能统计
   */
  getAPIPerformanceStats(): {
    totalCalls: number;
    averageResponseTime: number;
    slowestCall: APICallMetrics | null;
    errorRate: number;
  } {
    if (this.apiMetrics.length === 0) {
      return {
        totalCalls: 0,
        averageResponseTime: 0,
        slowestCall: null,
        errorRate: 0
      };
    }
    
    const totalResponseTime = this.apiMetrics.reduce((sum, metric) => sum + metric.responseTime, 0);
    const errorCount = this.apiMetrics.filter(metric => !metric.success).length;
    const slowestCall = this.apiMetrics.reduce((slowest, current) => 
      current.responseTime > slowest.responseTime ? current : slowest
    );
    
    return {
      totalCalls: this.apiMetrics.length,
      averageResponseTime: Math.round(totalResponseTime / this.apiMetrics.length),
      slowestCall,
      errorRate: Math.round((errorCount / this.apiMetrics.length) * 100)
    };
  }
  
  /**
   * 清理性能数据
   */
  clearMetrics(): void {
    this.pageMetrics.clear();
    this.apiMetrics = [];
    console.log('🧹 性能监控数据已清理');
  }
  
  /**
   * 停止监控
   */
  stop(): void {
    if (this.memoryCheckInterval) {
      clearInterval(this.memoryCheckInterval);
      this.memoryCheckInterval = undefined;
    }
    this.clearMetrics();
    console.log('⏹️ 性能监控已停止');
  }
}

/**
 * 性能监控装饰器
 */
export function monitorPerformance(pageName?: string) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    const monitor = PerformanceMonitor.getInstance();
    
    descriptor.value = async function (...args: any[]) {
      const methodName = pageName || `${target.constructor.name}.${propertyKey}`;
      const startTime = Date.now();
      
      try {
        const result = await originalMethod.apply(this, args);
        const endTime = Date.now();
        
        console.log(`⚡ ${methodName} 执行完成，耗时: ${endTime - startTime}ms`);
        
        return result;
      } catch (error) {
        const endTime = Date.now();
        console.error(`❌ ${methodName} 执行失败，耗时: ${endTime - startTime}ms`, error);
        throw error;
      }
    };
    
    return descriptor;
  };
}

/**
 * 创建API性能监控包装器
 */
export function createAPIMonitor() {
  const monitor = PerformanceMonitor.getInstance();
  
  return {
    /**
     * 包装请求函数以监控性能
     */
    wrapRequest<T extends (...args: any[]) => Promise<any>>(requestFn: T, url: string, method: string): T {
      return (async (...args: any[]) => {
        const startTime = Date.now();
        let success = true;
        let errorMessage: string | undefined;
        
        try {
          const result = await requestFn(...args);
          return result;
        } catch (error) {
          success = false;
          errorMessage = error instanceof Error ? error.message : String(error);
          throw error;
        } finally {
          const endTime = Date.now();
          
          monitor.recordAPICall({
            url,
            method,
            startTime,
            endTime,
            responseTime: endTime - startTime,
            success,
            errorMessage
          });
        }
      }) as T;
    }
  };
}

/**
 * 页面性能监控混入
 */
export const performanceMonitorMixin = {
  data() {
    return {
      _performanceMonitor: PerformanceMonitor.getInstance(),
      _pageName: ''
    };
  },
  
  onLoad(this: any) {
    this._pageName = this.$options?.name || 'unknown';
    this._performanceMonitor.startPageMonitoring(this._pageName);
  },
  
  onReady(this: any) {
    this._performanceMonitor.endPageLoading(this._pageName);
  },
  
  mounted(this: any) {
    this.$nextTick(() => {
      this._performanceMonitor.endPageRendering(this._pageName);
    });
  },
  
  onUnload() {
    // 可以在这里记录页面停留时间等指标
  }
};

/**
 * 获取性能监控实例
 */
export const getPerformanceMonitor = () => PerformanceMonitor.getInstance();

/**
 * 便捷的性能测量函数
 */
export async function measurePerformance<T>(
  operation: () => Promise<T> | T,
  label: string
): Promise<T> {
  const startTime = Date.now();
  
  try {
    const result = await operation();
    const endTime = Date.now();
    
    console.log(`⚡ ${label} 完成，耗时: ${endTime - startTime}ms`);
    
    return result;
  } catch (error) {
    const endTime = Date.now();
    console.error(`❌ ${label} 失败，耗时: ${endTime - startTime}ms`, error);
    throw error;
  }
}

// 导出默认实例
export default PerformanceMonitor.getInstance();